package git.soulbgm.common.mapper;

import git.soulbgm.common.annotation.IdBuild;
import git.soulbgm.common.enums.IdType;
import org.apache.ibatis.mapping.MappedStatement;
import tk.mybatis.mapper.entity.EntityColumn;
import tk.mybatis.mapper.mapperhelper.EntityHelper;
import tk.mybatis.mapper.mapperhelper.MapperHelper;
import tk.mybatis.mapper.mapperhelper.MapperTemplate;
import tk.mybatis.mapper.mapperhelper.SqlHelper;

import java.util.Set;

/**
 * MySqlProvider实现类，MySQL方法实现类
 *
 * @author SoulBGM
 */
public class MySqlProvider extends MapperTemplate {

    public MySqlProvider(Class<?> mapperClass, MapperHelper mapperHelper) {
        super(mapperClass, mapperHelper);
    }

    /**
     * 批量插入
     *
     * @param ms
     */
    public String insertList(MappedStatement ms) {
        final Class<?> entityClass = getEntityClass(ms);
        Set<EntityColumn> pkColumns = EntityHelper.getPKColumns(entityClass);
        boolean flag = false;
        for (EntityColumn column : pkColumns) {
            IdBuild idBuild = column.getEntityField().getAnnotation(IdBuild.class);
            if (idBuild != null) {
                flag = idBuild.value() == IdType.JDBC;
                if (flag) {
                    break;
                }
            }
        }
        //开始拼sql
        StringBuilder sql = new StringBuilder();
        sql.append("<bind name=\"listNotEmptyCheck\" value=\"@tk.mybatis.mapper.util.OGNL@notEmptyCollectionCheck(list, '" + ms.getId() + " 方法参数为空')\"/>");
        sql.append(SqlHelper.insertIntoTable(entityClass, tableName(entityClass), "list[0]"));
        sql.append(SqlHelper.insertColumns(entityClass, flag, false, false));
        sql.append(" VALUES ");
        sql.append("<foreach collection=\"list\" item=\"record\" separator=\",\" >");
        sql.append("<trim prefix=\"(\" suffix=\")\" suffixOverrides=\",\">");
        //获取全部列
        Set<EntityColumn> columnList = EntityHelper.getColumns(entityClass);
        //当某个列有主键策略时，不需要考虑他的属性是否为空，因为如果为空，一定会根据主键策略给他生成一个值
        for (EntityColumn column : columnList) {
            if (flag) {
                if (!column.isId() && column.isInsertable()) {
                    sql.append(column.getColumnHolder("record") + ",");
                }
            } else {
                if (column.isInsertable()) {
                    sql.append(column.getColumnHolder("record") + ",");
                }
            }
        }
        sql.append("</trim>");
        sql.append("</foreach>");

        if (flag) {
            // 反射把MappedStatement中的设置主键名
            EntityHelper.setKeyProperties(pkColumns, ms);
        }

        return sql.toString();
    }

}
